<?php
    session_start();
    error_reporting(E_ALL);
    if(!isset($_SESSION['user'])){
        header("location:index.php");
    }
?>
<!DOCTYPE html>
<html>
	<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<script src="assets/js/jquery-1.8.1.min.js"></script>
		<script src="assets/js/bootstrap.min.js"></script>
		<link href="assets/css/bootstrap.min.css" rel="stylesheet">
        <link href="assets/css/customized.css" rel="stylesheet">
		<script src="assets/js/pushstream.js"></script>
        <title>test</title>
	</head>
    <body>
	<?php
        $db = new SQLite3('chatroom.db');
        $userName = $_SESSION['username'];
		//显示当前用户的基本信息
        $sql = "select * from user where name = '$userName'";
		$result = $db->query($sql);//$result = mysql_query($sql,$con);//找出用户
        if(!$row = $result->fetchArray(SQLITE3_ASSOC)){
            unset($_SESSION['username']);
            session_destroy();
            ?>
            <script>
                alert("账户不存在");
                window.location.href = "index.php";
            </script>
            <?php
        }else{
            $sql = "update user set online = 1 where name = '$userName'";
            $db->exec($sql);
            $userMotto = $row['motto'];
            $userNickname = $row['nickname'];
            $userIcon = $row['icon_path'];
        }
		?>
    <div id="frame-contents">
        <div class="container-customized">
            <div id="header">
            </div>
            <div id="body">
                <div id="titleBar">
                    <div class="text-center">
                    neotel聊天室 beta版
                    </div>
                </div>
                <div id="personal-info">
                    <div class="personal-icon right">
                        <img src="assets/img/icon/<?=$userIcon?>.jpg" alt="icon"/>
                    </div>
                    <div class="personal-id right">
                        <span><?=$row['nickname']?></span>
                        <button type="button" class="btn btn-customized btn-xs" id="group-member" data-toggle="modal" data-target="#group-modal" style="display:none;color:#fff">查看全部</button>
                        <button type="button" class="btn btn-customized btn-xs" id="invite" data-toggle="modal" data-target="#inviteModal">
                            加人
                        </button>
                    </div>

                    <div class="personal-motto right">
                        <?=$row['motto']?>
                    </div>
                </div>
                <div id="widget" >
                <?php
                $sql = "select * from user where online = 1 and name <> '$userName'";
                $result = $db->query($sql);
                $userOnlineSet = array();
                while( $row = $result->fetchArray(SQLITE3_ASSOC) ){
                    $userOnlineSet[$row['name']] = array("nickname"=> $row['nickname'],"motto" =>$row['motto'],"icon" =>$row['icon_path'],"everTalk" => false);
                    ?>
                        <div class="one-online" receiver="<?=$row['name']?>" >
                            <div class="one-online-icon">
                                <img src="assets/img/icon/<?=$row['icon_path']?>.jpg">
                                <span class='red-point'></span>
                                <span class='grey-cross'></span>
                            </div>
                            <div class="one-online-name">
                                <?=$row['nickname']?>
                            </div>
                            <div class="one-online-motto">
                                <?=$row['motto']?>
                            </div>
                        </div>
                    <?php
                }
                $userOnlineSet =json_encode($userOnlineSet);
                ?>
                </div>
                <div id="message">
                </div>
                <div id="message-input-container" style="display:none">
                    <textarea  id="message-input" placeholder="输入聊天信息"></textarea>
                    <button type="button" class="btn-xs btn-customized btn-success btn-group-justified">回复</button>
                </div>
            </div>
            <div class="text-center footer-bar">
                <button type="button" class="blkbutton" id="back-to-widget">&nbsp;返回面板&nbsp;&nbsp;</button>
                <button type="button" class="blkbutton" id="log-out">&nbsp;退出聊天室</button>
            </div>
        </div>
    </div>

    <div class="modal fade" id="inviteModal" role="dialog">
        <div class="modal-dialog" style="max-width: 400px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" >邀请聊天</h4>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="confirm-invite">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="group-modal" role="dialog">
        <div class="modal-dialog" style="max-width: 400px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">群聊成员</h4>
                </div>
                <div class="modal-body">
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="person_icon">
        <div class="modal-dialog" style="max-width: 400px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="myModalLabel">更改头像</h4>
                </div>
                <div class="modal-body">
                    <p>&nbsp默认头像</p>
                    <div class="row">
                        <div class="col-xs-4 col-xs-offset-4">
                            <div class="icon" value="1"><img src="assets/img/icon/1.jpg"></div>
                        </div>
                    </div> 
                    <p>&nbsp男</p>
                    <div class="row">
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="11"><img src="assets/img/icon/11.jpg"></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="13"><img src="assets/img/icon/13.jpg"></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="14"><img src="assets/img/icon/14.jpg"></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="15"><img src="assets/img/icon/15.jpg"></button>
                        </div>
                    </div>
                    <p>&nbsp女</p>
                    <div class="row">
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="22"><img src="assets/img/icon/22.jpg"/></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="23"><img src="assets/img/icon/23.jpg"></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none" value="24"><img src="assets/img/icon/24.jpg"></button>
                        </div>
                        <div class="col-xs-3">
                            <button type="button" class="icon padding-none"  value="25"><img src="assets/img/icon/25.jpg"></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="receiver-information" role="dialog">
        <div class="modal-dialog" style="max-width: 400px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="myModalLabel">详细资料</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="icon"><img src="assets/img/icon/1.jpg"></div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6 text-right">
                            昵称
                        </div>
                        <div class="col-xs-6" id="information-nickname"></div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6 text-right">
                            个性签名
                        </div>
                        <div class="col-xs-6" id="information-motto"></div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6 text-right">
                            在线状态
                        </div>
                        <div class="col-xs-6" id="information-state"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    </body>
</html>
<script>
    var sender = <?='"'.$userName.'"'?>;
    var senderMotto = <?='"'.$userMotto.'"'?>;
    var senderNickname = <?='"'.$userNickname.'"'?>;
    var senderIcon = <?='"'.$userIcon.'"'?>;
    var receiver ;
    var nameSet = $.parseJSON(<?="'".$userOnlineSet."'"?>);
    var message_history = new Array();

    function choose(){
        senderIcon = $(this).attr("value");
        $(".personal-icon img").attr("src","assets/img/icon/"+senderIcon+".jpg");
        var username = sender;
        $.ajax({
            type: "post",
            url: "register_submit.php",
            dataType: "json",
            data: { icon_path:senderIcon, name: username }
        });
        var message = new Array("iconChange", sender, senderIcon);
        ps.sendMessage( JSON.stringify( message ) );//向channel中push消息
        $("table[sender='"+sender+"'] ").find(".one-icon img").attr("src","icon/"+senderIcon+".jpg");
        $("#person_icon").modal('hide');
    }

    function informationView(){
        if(nameSet[receiver]['everTalk'] != "group"){
            $("#receiver-information").find(".icon img").attr("src","assets/img/icon/"+nameSet[receiver]['icon']+".jpg");
            $("#information-nickname").html(nameSet[receiver]['nickname']);
            $("#information-motto").html(nameSet[receiver]['motto'])
            var onlineOrNot = ($("#widget .one-online[receiver='"+receiver+"']").attr("online")!="false");
            $("#information-state").html(onlineOrNot?"在线":"离线");
            $("#receiver-information").modal('show');
        }
    }


    function chat(){
        receiver = $(this).attr("receiver");
        $(".personal-icon").unbind('click');
        $(".personal-icon").click(informationView);
        $("#back-to-widget").show();
        $("#message").show();;
        $("table").hide();
        $("#message").find("table[chat='"+receiver+"']").show();
        $("#message div.history-tip").hide();
        $("#message div.history-tip[chat='"+receiver+"']").show();
        $("#widget").hide();
        $("#personal-info>.right").removeClass("right").addClass("left");
        $(".personal-id span").html(nameSet[receiver]['nickname']);
        $(".personal-icon img").attr("src","assets/img/icon/"+nameSet[receiver]['icon']+".jpg");
        $(".personal-motto").html(nameSet[receiver]['motto']);
        $("#invite").show();
        $(".invite-tip").hide();
        $(".invite-tip[chat='"+receiver+"']").show();
        $("#message-input-container").show();
        $("#widget .one-online[receiver='"+receiver+"'] .one-online-icon .red-point").hide();
        var online = $(this).attr("online");
        if(online=="false"){
            $('#message-input').attr("disabled","disabled");
            $('#message-input+button').attr("disabled","disabled");
            $(".offline-tip").remove();
            $("#message").append('<div class="text-center offline-tip" >'
                +'对方已离线,信息发送功能关闭'
                +'</div>');
            $(".offline-tip").fadeIn(1000);
            $(".offline-tip").fadeOut(1000);
        }else if(nameSet[$(this).attr('receiver')]['everTalk']=="group"){
            $("#group-member").show();
            var inputElement = $("<input type='test' />");
            $("#message").find("table[receiver='"+receiver+"']").append(inputElement);
            inputElement.focus();
            inputElement.remove();
        }else{
            $('#message-input').removeAttr("disabled");
            $('#message-input+button').removeAttr("disabled");
            $(".offline-tip").remove();
            $("#message").append('<div class="text-center offline-tip" >'
                +'对方在线,信息发送功能开启'
                +'</div>');
            $(".offline-tip").fadeIn(1000);
            $(".offline-tip").fadeOut(1000);
        }
        //这部分改一下
        /*var inputElement = $("<input type='test' />");
        $(".offline-tip").append(inputElement);
        inputElement.focus();
        inputElement.remove();*/
        $("#inviteModal .modal-body").html("");
        $("#group-modal .modal-body").html("");

        $("#widget .one-online[receiver!='"+receiver+"']").each(function(){
            if($(this).attr("online")!="false"){
                if(nameSet[$(this).attr('receiver')]['everTalk']!="group"){
                    if(nameSet[receiver]['everTalk']!="group"){
                        var receiverTemp = $(this).attr("receiver");
                        $(this).clone().append("<input type='checkbox' class='invite-checkbox' name='"+receiverTemp+"'/>").appendTo("#inviteModal .modal-body");
                    }else{
                        var receiverTemp = $(this).attr("receiver");
                        var member = nameSet[receiver]['member'];
                        if(($.inArray(receiverTemp, member))<0){
                            $(this).clone().append("<input type='checkbox' class='invite-checkbox' name='"+receiverTemp+"'/>").appendTo("#inviteModal .modal-body");
                        }else{
                            $(this).clone().appendTo($("#group-modal .modal-body"));
                        };
                    }
                }
            }
        });
        if(nameSet[receiver]['everTalk']!="group"){
            $("#message").find("table[chat='"+receiver+"'] .my .one-message-id").eq(0).show();
            $("#message").find("table[chat='"+receiver+"'] .your .one-message-id").eq(0).show();
        }else{
            $("#message").find("table[chat='"+receiver+"'] .my .one-message-id").show();
            $("#message").find("table[chat='"+receiver+"'] .your .one-message-id").show();
        }
        $("#personal-icon").removeAttr("data-toggle").remove("data-target");

    }

    function backToWidget(){
        $("#back-to-widget").hide();
        $(".personal-icon").unbind('click');
        $(".personal-icon").click(function(){
            $("#person_icon").modal('show');
        });
        $("table.full-length").hide();
        $("#widget").show();
        $("#message").hide();
        $("#message-input-container").hide();
        $("#personal-info>.left").removeClass("left").addClass("right");
        $(".personal-id span").html(senderNickname);
        $(".personal-icon img").attr("src","assets/img/icon/"+senderIcon+".jpg");
        $(".personal-motto").html(senderMotto);
        $("#invite").hide();
        $("#group-member").hide();
        $("#personal-icon").attr("data-toggle","modal").attr("data-target","#person_icon");
    }

    function sendMsg(){
        var content = $("#message-input").val();
        if( content != "" ){
            var message = new Array("message", sender, receiver, content);
            ps.sendMessage( JSON.stringify( message ) );//向channel中push消息
            $("#message-input").val("");
            var myMessage = $('<table class="full-length" '+'chat="'+receiver+'" sender="'+sender+'">'
                +'<tbody>'
                +'<tr class="one-respond">'
                +'<td class="one-message-container">'
                +'<div class="my one-message">'
                +'<div class="one-message-id">'
                +senderNickname
                +'</div>'
                +'<div>'
                +content
                +'</div>'
                +'<div class="right triangle"></div>'
                +'<div class="right triangle triangle-inner"></div>'
                +'</div>'
                +'</td>'
                +'<td class="one-icon">'
                +'<div>'
                +'<img src="assets/img/icon/'+senderIcon+'.jpg" />'
                +'</div>'
                +'</td>'
                +'</tr>'
                +'</tbody>'
                +'</table>');
            $("#message").append(myMessage);
            var inputElement = $("<input type='test' />");
            myMessage.append(inputElement);
            inputElement.focus();
            inputElement.remove();
            if(nameSet[receiver]['everTalk']!="group"){
                $("table[chat='"+receiver+"'] .my .one-message-id").eq(0).show();
                message_history[message_history.length] = {"content":content, "sender":sender, "receiver":receiver};
                nameSet[receiver]['everTalk'] = true;
            }else{
                $("table[chat='"+receiver+"'] .my .one-message-id").show();
            }
        }
    }

    function isEmptyObj(obj){ var e;for(e in obj){return false} return true }

    function sendOffline(){
        for(var temp in nameSet){
            if(nameSet[temp]["everTalk"]==false || nameSet[temp]["everTalk"]=="group" ){
                delete nameSet[temp];
            }
        }
        if(!isEmptyObj(nameSet)){
            message_history.push(nameSet);//下线存储nameSet
            localStorage[sender] = JSON.stringify(message_history);
        }
        var message = new Array("offline", sender);
        ps.sendMessage( JSON.stringify( message ) );
        $.ajax({
            url: "logout.php",
            type: "post",
            dataType:'json',
            data:{"username":sender,"mode":"keep-session"}
        });
    }

    function logOut(){
        for(var temp in nameSet){
            if(nameSet[temp]["everTalk"]==false || nameSet[temp]["everTalk"]=="group" ){
                delete nameSet[temp];
            }
        }
        if(!isEmptyObj(nameSet)){
            message_history.push(nameSet);//下线存储nameSet
            localStorage[sender] = JSON.stringify(message_history);
        }
        var message = new Array("offline", sender);
        ps.sendMessage( JSON.stringify( message ) );
        $.ajax({
            url: "logout.php",
            type: "post",
            dataType:'json',
            data:{"username":sender,"mode":"unset-session"}
        });
        $(window).unbind("beforeunload");
        alert("注销成功");
        window.location.href = "index.php";
    }

    function _manageEvent( eventMessage ){
        if( eventMessage != '' )
        {
            var msg = $.parseJSON(eventMessage);
            if( msg[0] == "message" ){
                if(msg[1] != sender){
                    var receiverTemp;
                    if (nameSet[msg[2]]&&nameSet[msg[2]]['everTalk'] == "group"){
                        receiverTemp = msg[2];
                    }else if( msg[2] == sender ){
                        receiverTemp = msg[1];
                        if( nameSet[msg[1]]["everTalk"] == false ){
                            nameSet[msg[1]]["everTalk"] = true;
                        }//修改新上线的没和我聊过天的人的everTalk

                        //更新message_history
                        message_history[message_history.length] = {"content":msg[3], "sender":msg[1], "receiver":msg[2]};
                    }
                    var chatting = !$("#widget .one-online[receiver='"+receiverTemp+"']").is(":visible");
                    var yourMessage = $('<table class="full-length" '+'chat="'+receiverTemp
                        +'" sender="'+msg[1]+'" style="'+((chatting)?"":"display:none")+'" >'
                        +'<tbody>'
                        +'<tr class="one-respond">'
                        +'<td class="one-icon">'
                        +'<div>'
                        +'<img src="assets/img/icon/'+nameSet[msg[1]]['icon']+'.jpg" />'
                        +'</div>'
                        +'</td>'
                        +'<td class="one-message-container">'
                        +'<div class="your one-message">'
                        +'<div class="one-message-id">'
                        +nameSet[msg[1]]['nickname']
                        +'</div>'
                        +'<div>'
                        +msg[3]
                        +'</div>'
                        +'<div class="left triangle"></div>'
                        +'<div class="left triangle triangle-inner"></div>'
                        +'</div>'
                        +'</td>'
                        +'</tr>'
                        +'</tbody>'
                        +'</table>');
                    $("#message").append(yourMessage);
                    if(nameSet[receiverTemp]['everTalk']!="group"){
                        $("#message table[chat='"+receiverTemp+"'] .your .one-message-id").eq(0).show();
                    }else{
                        $("#message table[chat='"+receiverTemp+"'] .your .one-message-id").show();
                    }


                    if(!chatting){
                        $("#widget .one-online[receiver='"+receiverTemp+"'] .one-online-icon .red-point").show();
                    }else{
                        //var allMessage = $("table[chat='"+receiver+"']");
                        var inputElement = $("<input type='test' />");
                        //allMessage[allMessage.length-1].append(inputElement);
                        yourMessage.append(inputElement);
                        inputElement.focus();
                        inputElement.remove();
                    }
                }
            }else if( msg[0] == "offline" ){
                $("#widget .one-online[receiver='"+msg[1]+"']").attr("online","false");
                $("#widget .one-online[receiver='"+msg[1]+"'] .grey-cross").show();
                $("#inviteModal .modal-body .one-online[receiver="+msg[1]+"]").hide();
                if($("#message").is(":visible")){
                    if(msg[1] == receiver){
                        $(".offline-tip").remove();
                        $("#message").append('<div class="text-center offline-tip" chat="'+msg[1]+'">'
                        +'对方已离线,信息发送功能关闭'
                        +'</div>');
                        var offlineTipElement = $(".offline-tip");
                        offlineTipElement.fadeIn(1000);
                        offlineTipElement.fadeOut(1000);
                        var inputElement = $("<input type='test' />");
                        offlineTipElement.append(inputElement);
                        inputElement.focus();
                        inputElement.remove();
                        $('#message-input').attr("disabled","disabled");
                        $('#message-input+button').attr("disabled","disabled");
                    }else if($.inArray(msg[1],nameSet[receiver]['member'])>-1){
                        console.log("enter offline else if");
                        $(".offline-tip").remove();
                        $("#message").append('<div class="text-center offline-tip">'
                            +nameSet[msg[1]]['nickname']+'离线'
                            +'</div>');
                        var offlineTipElement = $(".offline-tip");
                        offlineTipElement.fadeIn(1000);
                        offlineTipElement.fadeOut(1000);
                        var inputElement = $("<input type='test' />");
                        offlineTipElement.append(inputElement);
                        inputElement.focus();
                        inputElement.remove();
                        $("#group-modal").find(".one-online[receiver='"+msg[1]+"'] .grey-cross").show();
                    }
                }
            }else if(msg[0] == "online"){
                if(msg[1] != sender){
                    if($("#widget .one-online[receiver='"+msg[1]+"']").length){
                        $("#widget .one-online[receiver='"+msg[1]+"']").removeAttr("online");
                        $("#widget .one-online[receiver='"+msg[1]+"'] .grey-cross").hide();
                        if($("#message").is(":visible")){
                            if(msg[1] == receiver){
                                $('#message-input').removeAttr("disabled");
                                $('#message-input+button').removeAttr("disabled");
                                $(".offline-tip").remove();
                                $("#message").append('<div class="text-center offline-tip">'
                                    +'对方在线,信息发送功能开启'
                                    +'</div>');
                                var offlineTipElement = $(".offline-tip");
                                offlineTipElement.fadeIn(1000);
                                offlineTipElement.fadeOut(1000);
                                var inputElement = $("<input type='test' />");
                                offlineTipElement.append(inputElement);
                                inputElement.focus();
                                inputElement.remove();
                            }else if($.inArray(msg[1],nameSet[receiver]['member'])>-1){
                                $(".offline-tip").remove();
                                $("#message").append('<div class="text-center offline-tip">'
                                    +nameSet[msg[1]]['nickname']+'上线'
                                    +'</div>');
                                var offlineTipElement = $(".offline-tip");
                                offlineTipElement.fadeIn(1000);
                                offlineTipElement.fadeOut(1000);
                                var inputElement = $("<input type='test' />");
                                offlineTipElement.append(inputElement);
                                inputElement.focus();
                                inputElement.remove();
                                $("#group-modal").find(".one-online[receiver='"+msg[1]+"'] .grey-cross").hide();
                            }
                            $("#inviteModal .modal-body .one-online[receiver="+msg[1]+"]").show();
                        }
                    }else{
                        var newPeople = $('<div class="one-online" receiver="'+msg[1]+'">'
                            +'<div class="one-online-icon">'
                            +'<img src="assets/img/icon/'+msg[4]+'.jpg">'
                            +'<span class="red-point"></span>'
                            +'<span class="grey-cross"></span>'
                            +'</div>'
                            +'<div class="one-online-name">'
                            +msg[2]
                            +'</div>'
                            +'</div>');
                        $("#widget").append(newPeople);
                        var infoTemp = new Array();
                        infoTemp['nickname'] = msg[2];
                        infoTemp['motto'] = msg[3];
                        infoTemp['everTalk'] = false;
                        infoTemp['icon'] = msg[4];
                        nameSet[msg[1]]=infoTemp;
                        $("#widget .one-online").click(chat);
                        $(newPeople).clone().append("<input type='checkbox' class='invite-checkbox' name="+receiver+"/>").appendTo("#inviteModal .modal-body");
                    }
                }
            }else if(msg[0]=="invite"){
                //msg 结构为 Array("invite",sender,peopleToInvite,groupName);
                if(msg[1]!=sender){
                    //如果'我'在成员之中
                    var index;
                    if((index = $.inArray(sender, msg[2]))>-1){
                        //如果这个群聊是新的 而不是旧群聊加人
                        if((typeof nameSet[msg[3]]) == "undefined"){
                            //console.log("enter if");
                            var infoTemp = new Array();
                            infoTemp['nickname'] = nameSet[msg[1]]['nickname']+" "+nameSet[msg[2][(index==0)?1:0]]['nickname']+" 等";
                            infoTemp['motto'] = " ";
                            infoTemp['everTalk'] = "group";
                            msg[2][index] = msg[1];
                            infoTemp['member'] = msg[2];
                            infoTemp['icon'] = '0';
                            nameSet[msg[3]]= infoTemp;
                            //下面有bug 直接复制元素 对于加入头像的模式就不行了
                            //向面板中加人
                            var newGroupGenerated;
                            newGroupGenerated = $("#widget .one-online[receiver='"+msg[1]+"']").clone().attr("receiver",msg[3]);
                            newGroupGenerated.children(".one-online-name").html(infoTemp['nickname']);
                            newGroupGenerated.find(".one-online-icon img").attr("src",'assets/img/icon/0.jpg');
                            //面板显示小红点 表示是新来的群聊对话
                            newGroupGenerated.find(".red-point").show();
                            newGroupGenerated.appendTo($("#widget"));
                            newGroupGenerated.click(chat);

                            //如果跟我正在聊天的这个人邀请的其他人
                            if($("#message").is(":visible")&&(receiver == msg[1])){
                                //那么就向"查看成员"的面板中添加成员
                                //同时 并"移除加人面板"中的待加成员
                                for(var i=0;i<infoTemp['member'].length;i++){
                                    $("#widget .one-online[receiver='"+infoTemp['member'][i]+"']").clone().appendTo($("#group-modal .modal-body"));
                                    $("#inviteModal .one-online[receiver='"+infoTemp['member'][i]+"']").remove();
                                }
                                //更改当前聊天的显示信息 包括聊天对象的昵称和签名
                                $("#personal-info .personal-id span").html(infoTemp['nickname']);
                                $("#personal-info .personal-motto").html(" ");
                                $("#personal-info .personal-icon img").attr("src",'assets/img/icon/0.jpg');
                                //显示"查看成员"按钮
                                $("#group-member").show();
                                receiver = msg[3];
                            }
                            //添加提示信息
                            $("#message").append("<div class='invite-tip' chat='"+msg[3]+"' style='display:"+((receiver == msg[3])?"block":"none")+"'>"+nameSet[msg[1]]['nickname']+"邀请"
                                +nameSet[msg[2][(index==0)?1:0]]['nickname']+" 等 加入群聊</div>");

                        }else{
                            //如果是旧群聊加人
                            //console.log("enter else if");
                            for(var i=nameSet[msg[3]]['member'].length;i<msg[2].length;i++){
                                nameSet[msg[3]]['member'].push(msg[2][i]);
                                //如果这个旧群就是当前正在聊天的群
                                if($("#message").is(":visible")&&(receiver == msg[1])){
                                    //那么就向"查看成员"的面板中添加成员
                                    //同时 并"移除加人面板"中的待加成员
                                    $("#widget .one-online[receiver='"+msg[2][i]+"']").clone().appendTo($("#group-modal .modal-body"));
                                    $("#inviteModal .one-online[receiver='"+msg[2][i]+"']").remove();
                                }
                            }
                            console.log(i);
                            $("#message").append("<div class='invite-tip' chat='"+msg[3]+"' style='display:"+((receiver == msg[3])?"block":"none")+"'>"+nameSet[msg[1]]['nickname']+"邀请"
                                +nameSet[msg[2][i-1]]['nickname']+" 等 加入群聊</div>");
                        }
                    }
                }
            }else if(msg[0]="iconChange"){
                if(msg[1] != sender){
                    nameSet[msg[1]]['icon'] = msg[2];
                    //改联系人头像
                    $(".one-online[receiver='"+msg[1]+"']").find(".one-online-icon img").attr("src","assets/img/icon/"+msg[2]+".jpg");
                    //改聊天记录头像
                    $("table[sender='"+msg[1]+"'] ").find(".one-icon img").attr("src","assets/img/icon/"+msg[2]+".jpg");
                    //改群聊头像
                    $(".personal-icon.left img").attr("src","assets/img/icon/"+msg[2]+".jpg");
                }
            }
        }
    }

    function invitePeople(){
        $("#inviteModal .modal-body input").removeAttr("checked");
    }

    function generateRandomString(){
        var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        var res = "";
        for(var i = 0; i < 10 ; i ++) {
            var id = Math.ceil(Math.random()*35);
            res += chars[id];
        }
        return res;
    }

    function invite(){
        var peopleToInvite = new Array();
        var chosenPeople = $("#inviteModal input:checked");
        if(chosenPeople.length){
            $("#inviteModal input:checked").each(function(){
                peopleToInvite.push($(this).attr("name"));
            });
            if(nameSet[receiver]['everTalk']!="group"){
                peopleToInvite.push(receiver);
                var groupName = generateRandomString();
                var inviteMessage = new Array("invite",sender,peopleToInvite,groupName);
                ps.sendMessage(JSON.stringify( inviteMessage ));
                var infoTemp = new Array();
                infoTemp['nickname'] = nameSet[receiver]['nickname']+" "+nameSet[peopleToInvite[0]]['nickname']+" 等";
                infoTemp['motto'] = " ";
                infoTemp['everTalk'] = "group";
                infoTemp['member'] = peopleToInvite;
                infoTemp['icon'] = "0";
                nameSet[groupName]=infoTemp;
                $("#group-member").show();
                //当前页面也需要show()
                //这个按钮的show加入到chat()中去
                //同时需要在chat()中对当前是否是群聊进行判断
                for(var i=0;i<peopleToInvite.length;i++){
                    $("#widget .one-online[receiver='"+peopleToInvite[i]+"']").clone().appendTo($("#group-modal .modal-body"));
                    $("#inviteModal .one-online[receiver='"+peopleToInvite[i]+"']").remove();
                }
                var newGroup = $("#widget .one-online[receiver='"+receiver+"']").clone();
                newGroup.find(".one-online-icon img").attr("src",'assets/img/icon/0.jpg');
                newGroup.attr("receiver",groupName).appendTo($("#widget"));
                $("#personal-info .personal-id span").html(infoTemp['nickname']);
                $("#personal-info .personal-motto").html(" ");
                $("#personal-info .personal-icon img").attr("src",'assets/img/icon/0.jpg');
                receiver = groupName;
                $("#widget .one-online[receiver='"+receiver+"']").click(chat);
                $("#widget .one-online[receiver='"+receiver+"'] .one-online-name").html(nameSet[receiver]['nickname']);
            }else{
                for(var i=0;i<peopleToInvite.length;i++){
                    nameSet[receiver]['member'].push(peopleToInvite[i]);
                    $("#widget .one-online[receiver='"+peopleToInvite[i]+"']").clone().appendTo($("#group-modal .modal-body"));
                    $("#inviteModal .one-online[receiver='"+peopleToInvite[i]+"']").remove();
                }
                var inviteMessage = new Array("invite",sender,nameSet[receiver]['member'],receiver);
                ps.sendMessage(JSON.stringify( inviteMessage ));
            }
            $('#inviteModal').modal('hide');
            $(".personal-id span").html(nameSet[receiver]['nickname']);
            $("#message").append("<div class='invite-tip' chat='"+receiver+"' >您邀请"
                +nameSet[peopleToInvite[0]]['nickname']+" 等 加入群聊</div>");
            //增加群聊联系人
            //更改群聊联系人
            //增加群聊联系人界面
        }else{
            alert("请添加至少一个群聊成员");
        }

    }

    $(function(){
            $("#back-to-widget").hide();
            var domain = window.location.host.split('.')[1];
            PushStream.LOG_LEVEL = 'debug';
            ps = new PushStream({
                host: "m."+domain+".cn",//这个地方配盒端push服务器的域名，格式为m.{%$domain%}.cn
                port: "80",//push服务器的端口，默认80
                timeout: "20000",
                modes: "websocket|longpolling|stream|eventsource"//4种模式，哪种写在前面，就优先用哪种
                //通常用websocket与longpolling这两种，前者有的手机浏览器支持不好，后者大部分浏览器都可以
                //websocket稳定性较好，longpolling相对较弱，容易丢消息
            });
            ps.onmessage = _manageEvent;//回调函数，收到消息的处理逻辑写在_manageEvent函数中
            _connect("channel_chat");//连接一个channel，参数为channel的id，这里假设是channel_chat
            var onlineMessage = function(){
                if(ps.readyState == PushStream.OPEN){
                    var onlineMessage = new Array("online",sender,senderNickname,senderMotto,senderIcon);
                    ps.sendMessage(JSON.stringify( onlineMessage ));
                }
            }

            ps.onstatuschange = onlineMessage;
            function _connect(channel)
            {
                ps.removeAllChannels();
                try
                {
                    ps.addChannel(channel);
                    ps.connect();
                }
                catch (error)
                {
                    alert(error);
                }
            }//连接一个channel

            $(".one-online").click(chat);
            $("#message-input+button").click(sendMsg);
            $(window).on("beforeunload", sendOffline);
            $("#back-to-widget").click(backToWidget);
            $("#log-out").click(logOut);

            $.ajax({
                url: "refresh.php",
                type: "post",
                dataType:'json',
                data:{"username":sender}
            });

            $("#invite").click(invitePeople);
            $("#confirm-invite").click(invite);

            $(".personal-icon").click(function(){
                $("#person_icon").modal('show');
            });

            $(".icon").click(choose);

            var temp_ = localStorage.getItem(sender);//读入和自己有关的聊天记录
            if( temp_ != null )
                message_history = $.parseJSON(temp_);

            if( temp_ ){

                //读message_history['infoset'],修改当前的nameSet  nameSet每个元素包括{ "nickname", "motto", "everTalk" } nameSet的索引是name
                if( message_history.length != 0 ){
                    for( var temp in message_history[message_history.length-1] ){//message_history['infoset']的结构等价于nameSet
                        if( typeof(nameSet[temp]) == "undefined" ){//如果和我聊天的某个人今天没上线
                            nameSet[temp] = message_history[message_history.length-1][temp];//把这个人的相关信息记入nameSet
                            var newPeople = $('<div class="one-online" receiver="'+temp+'" online="false">'
                                +'<div class="one-online-icon">'
                                +'<img src="assets/img/icon/'+message_history[message_history.length-1][temp]['icon']+'.jpg">'
                                +'<span class="red-point"></span>'
                                +'<span class="grey-cross"></span>'
                                +'</div>'
                                +'<div class="one-online-name">'
                                +message_history[message_history.length-1][temp]['nickname']
                                +'</div>'
                                +'</div>');
                            $("#widget").append(newPeople);
                            $("#widget .one-online").click(chat);
                        }else{
                            if( nameSet[temp]["everTalk"] == false ){//如果上线的这个人默认没有和我聊过天，但实际上聊过
                                nameSet[temp]["everTalk"] = true;
                            }
                        }
                    }//根据message_history['infoset'] 把 nameSet修改完毕
                    delete message_history[message_history.length-1];
                    message_history.length = message_history.length-1;
                    for(var i=0; i<=message_history.length-1; ++i ){
                        var perSentence = message_history[i];
                        if( perSentence["sender"] == sender){//发送方是自己

                            var myMessage = $('<table class="full-length" '+'chat="'+perSentence["receiver"]+'" sender="'+sender+'">'
                                +'<tbody>'
                                +'<tr class="one-respond">'
                                +'<td class="one-message-container">'
                                +'<div class="my one-message">'
                                +'<div class="one-message-id">'
                                +senderNickname
                                +'</div>'
                                +'<div>'
                                +perSentence["content"]
                                +'</div>'
                                +'<div class="right triangle"></div>'
                                +'<div class="right triangle triangle-inner"></div>'
                                +'</div>'
                                +'</td>'
                                +'<td class="one-icon">'
                                +'<div>'
                                +'<img src="assets/img/icon/'+senderIcon+'.jpg" />'
                                +'</div>'
                                +'</td>'
                                +'</tr>'
                                +'</tbody>'
                                +'</table>');
                            $("#message").append(myMessage);

                        }else if( perSentence["receiver"] == sender ){//接收方是自己
                            console.log(perSentence);
                            console.log(nameSet);
                            var yourMessage = $('<table class="full-length" '+'chat="'+perSentence["sender"]+'"  sender="'+perSentence["sender"]+'">'
                                +'<tbody>'
                                +'<tr class="one-respond">'
                                +'<td class="one-icon">'
                                +'<div>'
                                +'<img src="assets/img/icon/'+nameSet[perSentence["sender"]]['icon']+'.jpg" />'
                                +'</div>'
                                +'</td>'
                                +'<td class="one-message-container">'
                                +'<div class="your one-message">'
                                +'<div class="one-message-id">'
                                +nameSet[perSentence["sender"]]['nickname']
                                +'</div>'
                                +'<div>'
                                +perSentence["content"]
                                +'</div>'
                                +'<div class="left triangle"></div>'
                                +'<div class="left triangle triangle-inner"></div>'
                                +'</div>'
                                +'</td>'
                                +'</tr>'
                                +'</tbody>'
                                +'</table>');
                            $("#message").append(yourMessage);
                        }
                    }
                }



            }//聊天从窗口对话写入完毕



            //根据nameSet中的 everTalk 向message中加入历史信息提示
            for( temp in nameSet ){
                if(nameSet[temp]["everTalk"] == true){//如果这个人和我聊过天
                    $("#message").append("<div class='history-tip text-center' chat='" + temp + "'>以上是历史信息</div>");
                }
            }
        }
    );
</script>


